/*
 * TCPSocket.h
 *
 *  Created on: Mar 14, 2011
 *      Author: sms103
 */

#ifndef TCPSOCKET_H_
#define TCPSOCKET_H_

#include <iostream>
#include <errno.h>
#include <poll.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include "IPAddress.h"

using namespace std;

#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 18181828
#endif

class TCPSocket {
public:

	/* Gets a blank tcp socket descriptor from kernel, not bound or connected */
	TCPSocket();

	/*  Constructs the TCPSocket object on an existing socket descriptor */
	TCPSocket(int openSockDesc);

	bool socketCreatedSuccessfully();


	const char * getError();

	/* Attempts to connect this socket to the specified host and port
	 * returns true on success and false on failure */
	bool tcpConnect(IPAddress &ipAddr, int portNumber);

	/* Attempts to bind to localhost address and the specified port number.
	 * returns true on success, false on failure*/
	bool tcpBind(int portNumber);

	/* Listens for incoming connections on this socket. Call bind first.*/
	bool tcpListen(int backLog=128);

	/* Blocks until an incoming connection arrives or a timeout occurs. Returns a new TCPSocket
	 * representing the newly opened socket. Returns null if timeout occured before a new connection.
	 * negative timeout represents infinfity*/
	TCPSocket * tcpAccept(int timeout=-1);

	/* Attempts to send len bytes from buf. returns actual number of bytes sent. */
	int tcpSend(void *buf,size_t len);

	/* Attempts to read len bytes into buf from this socket. returns number of
	 * bytes received. A return value of zero indicates this connection is closed.*/
	int tcpRecv(void *buf, size_t len);

	/**/
	//bool wouldBlock();

	/* Closes this connection. */
	int tcpClose();

	virtual ~TCPSocket();

private:
	int socketDescriptor;
	bool connected;
	struct sockaddr_in saddr_in;

};

#endif /* TCPSOCKET_H_ */
